const router = require('koa-router')();
const fs = require('fs');
const connection = require('./db'); // 导入数据库连接对象


let list 

router.get('/userslist', async (ctx) => {
  const query = 'SELECT * FROM userlist';
  try {
    // 使用 Promise 包装数据库查询操作
     list = await new Promise((resolve, reject) => {
      connection.query(query, function (error, results, fields) {
        if (error) reject(error);
        else resolve(results);
      });
    });
    // 将数据发送到前端
    ctx.body = list;
  } catch (err) {
    console.error(err);
    ctx.status = 500;
    ctx.body = { error: '服务器出错' };
  }
});
   /* try {
      // 读取json文件中的数据
      const data = fs.readFileSync('routes/uploads/users.json', 'utf8');
      const users = JSON.parse(data);
  
      // 将数据发送回前端
      ctx.body = users;
    } catch (err) {
      console.error(err);
      ctx.status = 500;
      ctx.body = { error: '服务器出错' };
    }*/
 

  router.post('/usersadd', function (ctx, next) {
    const newUser = ctx.request.body;
    console.log(newUser);
   const { name, phone, email, address } = newUser;
    const data = {
      name: name,
      phone: phone,
      email: email,
      address: address
    };
  
    const jsonData = JSON.stringify(data);
    const sql = `INSERT INTO userlist (name,phone,email,address) VALUES (?, ?, ?, ?)`;
    const params = [data.name,data.phone,data.email,data.address];
     connection.query(sql, params);

   /* fs.readFile('routes/uploads/users.json', (err, fileData) => {
      if (err) {
        console.error(err);
        ctx.body = 'Error saving data';
        
        return;
      }
      const users = JSON.parse(fileData);
      console.log(users);
      users.push(data);
      const usersdata = JSON.stringify(users);
      console.log(usersdata);

      
    fs.writeFile('routes/uploads/users.json', usersdata, (err) => {
      if (err) {
        console.error(err);
        ctx.body = 'Error saving data';
      } else {
        console.log('User added successfully');
        ctx.body = 'Data saved successfully';
      }
    });
    })*/
  
    ctx.body = 'this is a upload!'


  });

  router.delete('/userdelete', function (ctx, next) {

    const user = ctx.request.query;
    console.log(user['user[name]']);
    const del ="DELETE FROM userlist WHERE name = ?;";
    connection.query(del, user['user[name]'])


    /*fs.readFile('routes/uploads/users.json', (err, fileData) => {
      if (err) {
        console.error(err);
        ctx.body = 'Error saving data';
        
        return;
      }
      const userslist = JSON.parse(fileData);
      console.log(userslist);
    
      for (let i = 0; i < userslist.length; i++) {

        // 通过查找 userlist 对象中的属性来匹配要删除的用户
        if (userslist[i].name === user['user[name]'] && userslist[i].phone === user['user[phone]'] && userslist[i].email ===user['user[email]'] && userslist[i].address === user['user[address]']) {
          // 从 JavaScript 对象中删除该用户的信息
          userslist.splice(i, 1);
          break;
        }}
        // 将更新后的 JavaScript 对象转换为 JSON 格式
      const updatedData = JSON.stringify(userslist, null, 2);

        // 将更新后的 JSON 字符串写回到 JSON 文件中
      fs.writeFileSync('routes/uploads/users.json', updatedData, 'utf-8');
    })*/


    ctx.body = 'File deleted successfully'
  });


router.put('/userchange', function (ctx, next) {
  const newUser = ctx.request.body;
  ctx.body= 'successfully';
  const { name, phone, email, address } = newUser;
  const data = {
    name: name,
    phone: phone,
    email: email,
    address: address
  };

  const jsonData = JSON.stringify(data);

  let sql = 'update userlist set phone=?,email=?,address=? where name=?';
  const params = [data.phone,data.email,data.address,data.name];
  connection.query(sql, params);
 
  /*let users = JSON.parse(fs.readFileSync('routes/uploads/users.json', 'utf-8'));
  const updatedUsers = users.map(user => {
    if (user.email === email) {
      return { name, phone, email, address };
    } else {
      return user;
    }
  });
  fs.writeFileSync('routes/uploads/users.json', JSON.stringify(updatedUsers, null, 2));*/
 
  /*for (let i = 0; i < users.length; i++) {
    if (users.name === jsonData.name ||users.phone === jsonData.phone|| users.email ===jsonData.email|| users.address ===jsonData.address) {
      users[i].name= jsonData.name;
      users[i].phone = jsonData.phone;
      users[i].email =jsonData.email;
      users[i].address =jsonData.address;
    }
  }    console.log("1212121"+users);*/
});

  module.exports = router
  